from flask import Flask
from celery import Celery, Task
from celery.schedules import crontab



def register_celery(app: Flask) -> Celery:

    class CeleryConfig(object):
        broker_url: str = 'redis://127.0.0.1:6379/1'
        result_backend: str = 'redis://127.0.0.1:6379/2'
        imports: list = [
            "app.tasks"
        ]
        beat_schedule: dict = {

            'hello-celery': {
                'task': 'app.tasks.hello_celery',
                'schedule': crontab(),
                'args': ('world', )
            }

        }

    class FlaskTask(Task):
        def __call__(self, *args: object, **kwargs: object) -> object:
            with app.app_context():
                return self.run(*args, **kwargs)

    celery_app = Celery(
        app.name,
        task_cls=FlaskTask
    )
    celery_app.config_from_object(CeleryConfig)
    celery_app.set_default()
    app.extensions["celery"] = celery_app
    return celery_app
